In [1]:
%%writefile myfile.txt
Hello this is a text file
this is the second line
this is the third line
In [2]:
myfile = open('myfile.txt')
In [3]:
myfile = open('woopsmy.txt')
In [4]:
file = open('myfile.txt')
In [5]:
pwd
Out[5]:
In [6]:
ls
In [7]:
myfile.read()
Out[7]:
In [9]:
myfile.encoding()
In [13]:
myfile.seek(0) #resets the reader buffer.
Out[13]:
In [14]:
myfile.readlines()
Out[14]:
file paths required for different locations:
file = open("C:\Users\Russ\Documents\myfile.txt")
file = open("/Users/Russ/Documents/myfile.txt")
When opening files, they must be closed after use myfile.close() method. Or..............
In [16]:
with open ('myfile.txt') as mynewfile:
contents = mynewfile.read() #Don't have to worry about closing witht his method.
In [21]:
with open ('myfile.txt',mode='r') as myfile: #in a method bracket '(|' < place the cursor and press shift+tab .ipynb
contents = myfile.read()
In [22]:
contents
Out[22]:
In [23]:
with open ('myfile.txt',mode='w') as myfile: # in a method bracket '(|' < place the cursor and press shift+tab .ipynb
contents = myfile.write() # String contents missing, error reported.
In [24]:
with open ('myfile.txt',mode='w') as myfile: # in a method bracket '(|' < place the cursor and press shift+tab .ipynb
contents = myfile.write('hi') # String contents missing, NO error reported.
In [28]:
with open('myfile.txt',mode='r') as myfile:
new = myfile.read()
new
In [29]:
new
Out[29]:
In [30]:
%%writefile newone.txt
LINE ONE
LINE TWO
LINE 3
In [32]:
file2 = open('newone.txt')
In [36]:
file2.read()
Out[36]:
In [37]:
file2.seek(0)
Out[37]:
In [39]:
with open('newone.txt',mode='r') as f:
print(f.read())
In [42]:
with open('newone.txt',mode='a') as f:
f.write('\nfourth line')
In [43]:
with open('newone.txt',mode='r') as f:
print(f.read())
In [50]:
with open('jshdgfihwdik.txt',mode='w') as f: # The file is created if non-existent
f.write('I CREATED THIS FILE USING THE FOLLOWING METHOD\nwith open(\'jshdgfihwdik.txt\',mode=\'w\') as f:\n\tf.write(\'some random text\')')
In [51]:
with open('jshdgfihwdik.txt',mode='r') as f:
print(f.read())
In [ ]: